package com.enjoyor.soa.traffic.frame.support.validator;

import java.text.SimpleDateFormat;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.enjoyor.soa.traffic.frame.annotation.DateCheck;

public class DateValidator implements ConstraintValidator<DateCheck, String> {

    private String format;

    @Override
    public void initialize(DateCheck constraintAnnotation) {
        format = constraintAnnotation.format();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {

        if (value == null)
            return true;

        boolean convertSuccess = true;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setLenient(false);
        try {
            sdf.parse(value);
        } catch (Exception e) {
            convertSuccess = false;
        }
        return convertSuccess;
    }

}
